//
//  SimPhoto.m
//  SimPhotoBrowser
//
//  Created by Michael Waterfall on 17/10/2010.
//  Copyright 2010 d3i. All rights reserved.
//

#import "SimPhotoModel.h"
#import "SimPhotoBrowser.h"
#import "SDWebImageDecoder.h"
#import "SDWebImageManager.h"
#import "SDWebImageOperation.h"
#import <AssetsLibrary/AssetsLibrary.h>

@interface SimPhotoModel () {

    BOOL _loadingInProgress; //0:needLoading, 1:loading
    UIImage *_image;
    id <SDWebImageOperation> _webImageOperation;
        
}

- (void)imageLoadingComplete;

@end

@implementation SimPhotoModel


#pragma mark - Class Methods

+ (SimPhotoModel *)photoWithImage:(UIImage *)image {
	return [[SimPhotoModel alloc] initWithImage:image];
}

+ (SimPhotoModel *)photoWithURL:(NSURL *)url {
	return [[SimPhotoModel alloc] initWithURL:url];
}

#pragma mark - Init
- (id)initWithImage:(UIImage *)image {
	if ((self = [super init])) {
		_image = image;
	}
	return self;
}

- (id)initWithURL:(NSURL *)url {
	if ((self = [super init])) {
		_photoURL = [url copy];
	}
	return self;
}

#pragma mark - SimPhoto Protocol Methods
- (void)loadImage {
    if (_loadingInProgress)
        return;
    
    _loadingInProgress = YES;
    @try {
        if (_loadedImage) {
            [self imageLoadingComplete];
        } else {
            [self tryLoadImage];
        }
    }
    @catch (NSException *exception) {
        _loadedImage = nil;
        _loadingInProgress = NO;
        [self imageLoadingComplete];
    }
    @finally {
    }
}

- (void)tryLoadImage
{
    if (_image) {
        _loadedImage = _image;
        [self imageLoadingComplete];
    }
    else if (_photoURL) {
        if ([[[_photoURL scheme] lowercaseString] isEqualToString:@"assets-library"]) {
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                @autoreleasepool {
                    @try {
                        ALAssetsLibrary *assetslibrary = [[ALAssetsLibrary alloc] init];
                        [assetslibrary assetForURL:_photoURL
                                       resultBlock:^(ALAsset *asset){
                                           ALAssetRepresentation *rep = [asset defaultRepresentation];
                                           CGImageRef iref = [rep fullScreenImage];
                                           if (iref) {
                                               _loadedImage = [UIImage imageWithCGImage:iref];
                                           }
                                           [self imageLoadingComplete];
                                       }
                                      failureBlock:^(NSError *error) {
                                          [self imageLoadingComplete];
                                      }];
                    } @catch (NSException *e) {
                        [self imageLoadingComplete];
                    }
                }
            });
        } else if ([_photoURL isFileURL]) {
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                @autoreleasepool {
                    @try {
                        _loadedImage = [UIImage imageWithContentsOfFile:_photoURL.path];
                    } @finally {
                        [self imageLoadingComplete];
                    }
                }
            });
            
        } else {
            SDWebImageManager *manager = [SDWebImageManager sharedManager];
            if (![manager cachedImageExistsForURL:_photoURL]) {
                [[NSNotificationCenter defaultCenter] postNotificationName:kSimPhotoModelImageLoadBeginNoti
                                                                    object:self];
            };

            @try {
                _webImageOperation = [manager downloadImageWithURL:_photoURL
                                                           options:0
                                                          progress:^(NSInteger receivedSize, NSInteger expectedSize) {
                                                              if (expectedSize > 0) {
                                                                  float progress = receivedSize / (float)expectedSize;
                                                                  NSDictionary* dict = @{kSimPhotoNotiProgressKey : @(progress),
                                                                                         kSimPhotoNotiPhotoKey : self};
                                                                  [[NSNotificationCenter defaultCenter] postNotificationName:kSimPhotoModelImageLoadProgressNoti object:dict];
                                                              }
                                                          }
                                                         completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
                                                             _webImageOperation = nil;
                                                             _loadedImage = image;
                                                             [self imageLoadingComplete];
                                                         }];
            } @catch (NSException *e) {
                _webImageOperation = nil;
                [self imageLoadingComplete];
            }
        }
    }
}

- (void)unloadImage
{
    [self cancelImageLoad];
    _loadingInProgress = NO;
	_loadedImage = nil;
}

- (void)imageLoadingComplete
{
    _loadingInProgress = NO;
    SafeSyncOnMainThread([[NSNotificationCenter defaultCenter] postNotificationName:kSimPhotoModelImageLoadFinishNoti
                                                                             object:self];
    )
}



- (void)cancelImageLoad
{
    if (_webImageOperation) {
        [_webImageOperation cancel];
        _loadingInProgress = NO;
    }
}

@end
